package com.yj.springbootstudy.mulThread.demo;

/**
 * 两阶段终止模式
 *  如何优雅的停止线程
 *
 */
public class TwoPhaseTerminalTest {
    public static void main(String[] args) throws InterruptedException {
        TowPhaseTerminal tpt = new TowPhaseTerminal();
        tpt.start();
        Thread.sleep(3000);
        tpt.stop();
    }
}

class TowPhaseTerminal{

    private Thread monitor;

    public void start(){
        monitor = new Thread(()->{
            Thread current = Thread.currentThread();
           while (true){
               //如果被打断了
               if (current.isInterrupted()){
                   System.out.println("料理后事");
                   break;
               }
               try {
                   Thread.sleep(1000); //如果在此处被打断，打断标志会为false
                   System.out.println("执行监控记录"); //如果在此处被打断，打断标志为true
               } catch (InterruptedException e) {
                   e.printStackTrace();
                   current.interrupt(); //因为如果是sleep wait join 阻塞状态被打断 打断标志为false 需要重新设置打断标志
               }
           }
        });
        monitor.start();
    }

    public void stop(){
        monitor.interrupt();
    }


}
